//
//  HiWebController.m
//  HiCar
//
//  Created by 丁一 on 2018/12/12.
//  Copyright © 2018 丁一. All rights reserved.
//

#import "HiWebController.h"
#import "Masonry.h"
#import <WebKit/WebKit.h>

@interface HiWebController ()<WKNavigationDelegate, WKUIDelegate>

@property (nonatomic, strong) UIProgressView *myProgressView;
@property (nonatomic, strong) WKWebView      *webView;

@end

@implementation HiWebController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"加载...";
    self.view.backgroundColor = LineColor;
    [self setnavback];
    [self loadwebview];
}

- (void)loadwebview{
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_Url_string?_Url_string:@"http://moche.online"]]];
    [self.view addSubview:self.myProgressView];
    [self.myProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(NAV_Height);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(1.5);
    }];
}

#pragma mark - getter and setter
- (UIProgressView *)myProgressView{
    if (_myProgressView == nil) {
        _myProgressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, NAV_Height, RECRWITCH, 1)];
        _myProgressView.tintColor = Bluecolor;
        _myProgressView.trackTintColor = [UIColor whiteColor];
    }
    
    return _myProgressView;
}

- (WKWebView *)webView{
    if(_webView == nil){
        _webView = [[WKWebView alloc] init];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.opaque = NO;
        _webView.multipleTouchEnabled = YES;
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _webView;
}

// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.myProgressView.alpha = 1.0f;
        [self.myProgressView setProgress:newprogress animated:YES];
        if (newprogress >= 1.0f) {
            [UIView animateWithDuration:0.3f
                                  delay:0.3f
                                options:UIViewAnimationOptionCurveEaseOut
                             animations:^{
                                 self.myProgressView.alpha = 0.0f;
                             }
                             completion:^(BOOL finished) {
                                 [self.myProgressView setProgress:0 animated:NO];
                             }];
        }
        
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

// 记得取消监听
- (void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

#pragma mark - WKNavigationDelegate
/**
 *  页面开始加载时调用
 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"%s", __FUNCTION__);
    self.navigationItem.title = @"加载...";
}

/**
 *  当内容开始返回时调用
 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"%s", __FUNCTION__);
    if (webView.title) {
        self.navigationItem.title = webView.title;
    }else{
        self.navigationItem.title = @"加载...";
    }
}

/**
 *  页面加载完成之后调用
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"%s", __FUNCTION__);
    if (webView.title) {
        self.navigationItem.title = webView.title;
    }else{
        self.navigationItem.title = @"加载...";
    }
}

/**
 *  加载失败时调用
 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    NSLog(@"%s", __FUNCTION__);
    self.navigationItem.title = @"加载失败";
}
//
///**
// *  接收到服务器跳转请求之后调用
// *
// *  @param webView      实现该代理的webview
// *  @param navigation   当前navigation
// */
//- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
//
//    NSLog(@"%s", __FUNCTION__);
//}
//
///**
// *  在收到响应后，决定是否跳转
// *
// *  @param webView            实现该代理的webview
// *  @param navigationResponse 当前navigation
// *  @param decisionHandler    是否跳转block
// */
//- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
//
////    // 如果响应的地址是百度，则允许跳转
////    if ([navigationResponse.response.URL.host.lowercaseString isEqual:@"www.baidu.com"]) {
////
////        // 允许跳转
//////        decisionHandler(WKNavigationResponsePolicyAllow);
//////        return;
////    }
//    // 不允许跳转
//    decisionHandler(WKNavigationResponsePolicyCancel);
//}
//
///**
// *  在发送请求之前，决定是否跳转
// *
// *  @param webView          实现该代理的webview
// *  @param navigationAction 当前navigation
// *  @param decisionHandler  是否调转block
// */
//- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//
//    // 如果请求的是百度地址，则延迟5s以后跳转
////    if ([navigationAction.request.URL.host.lowercaseString isEqual:@"www.baidu.com"]) {
////
////        //        // 延迟5s之后跳转
////        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
////        //
////        //            // 允许跳转
////        //            decisionHandler(WKNavigationActionPolicyAllow);
////        //        });
////
////        // 允许跳转
//////        decisionHandler(WKNavigationActionPolicyAllow);
//////        return;
////    }
//    // 不允许跳转
//    decisionHandler(WKNavigationActionPolicyCancel);
//}

@end
